//
//  TableViewController.m
//  hhhhhhh
//
//  Created by 方伟 on 16/7/22.
//  Copyright © 2016年 倪新伟. All rights reserved.
//

#import "TableViewController.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "OneTableViewCell.h"
#import "Model.h"
#import "DQTextFild.h"
#define KUIScreen  [UIScreen mainScreen].bounds.size
// RGB颜色数值设置
#define RGBCOLOR(r,g,b) ([UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1])
#define kGrayColor  RGBCOLOR(0xe3,0xe3,0xe3)
@interface TableViewController ()



/** AFN请求管理者 */
@property (nonatomic, strong) AFHTTPSessionManager *manager;

/** 列表 数据*/
@property(strong,nonatomic)NSMutableArray *list;
@property (nonatomic,strong)DQTextFild *drugSearchFiled;
@property (nonatomic,strong)NSPredicate *predicate;
@property (nonatomic,strong)NSMutableArray *nameList;
@property (nonatomic,strong)NSArray *heheArray;
@end

static NSString * const OneId = @"one";
@implementation TableViewController
- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (NSMutableArray *)list{
    if (_list == nil) {
        _list = [NSMutableArray array];
    }
    return _list;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.nameList = [NSMutableArray array];
    self.heheArray = [NSArray array];
    [self setupTableView];
    [self loadList];
    
    
}
/**
 *  控件的初始化
 */
- (void)setupTableView{
    // 注册
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OneTableViewCell class]) bundle:nil] forCellReuseIdentifier:OneId];
    
//    self.tableView.rowHeight = 100;
    //搜索框
    self.drugSearchFiled = [[DQTextFild alloc] initWithFrame:CGRectMake(30, 15,KUIScreen.width-60 , 30)];
    self.drugSearchFiled.placeholder = @"请输入药品名称";
    self.drugSearchFiled.layer.borderWidth = 1;
    self.drugSearchFiled.layer.masksToBounds = YES;
    self.drugSearchFiled.layer.borderColor = kGrayColor.CGColor;
    self.drugSearchFiled.layer.cornerRadius = 3;
    UIImageView *img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"utils_search"]];
    img.frame = CGRectMake(10, 5,20,20);
    self.drugSearchFiled.leftView  = img;
    self.drugSearchFiled.leftViewMode = UITextFieldViewModeAlways;
    
    
    [self.drugSearchFiled addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.tableView.tableHeaderView = self.drugSearchFiled;
}

/**
 * 加载左侧的类别数据
 */
- (void)loadList{
    [self.manager.requestSerializer setValue:@"59c97d078d6df6e6ebe1339918de6f98" forHTTPHeaderField:@"apikey"];
    _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [self.manager GET:@"http://apis.baidu.com/medlive/drugs/drugapi?type=list&key=%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97&page=1&pagesize=10&drugid=8" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//       NSLog(@"%@",responseObject);
        NSDictionary *dic = responseObject[@"retData"];
        NSArray *array = dic[@"data"];
//        NSLog(@"%@",array);
        for (NSDictionary *d in array) {
            Model *model = [[Model alloc] init];
            [model setValuesForKeysWithDictionary:d];
            [self.list addObject:model];
            [self.nameList addObject:model.dsName];
//            NSLog(@"%@",self.list);
        }
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"sdfsdaf");
        NSLog(@"%@",error);
    }];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.heheArray.count>0) {
        return self.heheArray.count;
    }else{
         return self.list.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    OneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:OneId];
  
    if (self.heheArray.count>0) {
        
        cell.subjiectLabel.text = self.heheArray[indexPath.row];
        
    }else{
        Model *model = self.list[indexPath.row];
        cell.subjiectLabel.text = model.dsName;
    }
    return cell;
}
- (void)textFieldDidChange:(UITextField *)textField{
    self.predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",textField.text];
    self.heheArray = [self.nameList filteredArrayUsingPredicate:self.predicate];

    [self.tableView reloadData];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
